package com.msh.business;

import com.msh.annotations.ProcessType;
import com.msh.common.VMSystem;
import com.msh.contract.SupplyCfg;
import com.msh.feignService.VMService;
import com.msh.http.viewModel.TaskDetailsViewModel;
import com.msh.http.viewModel.TaskViewModel;
import com.msh.service.TaskService;
import com.msh.utils.JsonUtil;
import com.msh.viewmodel.VendingMachineViewModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.stream.Collectors;

/**
 * @author :zhangchuanfu
 * @Date :2023/1/13
 * @Time :16:48
 * @description : 补货工单消息处理
 */
@Component
@ProcessType("supplyTask")
@Slf4j
public class SupplyTaskHandler implements MsgHandler{
    @Autowired
    private VMService vmService;
    @Autowired
    private TaskService taskService;
    @Override
    public void process(String jsonMsg) {

        try {
            //解析协议内容
            SupplyCfg supplyCfg = JsonUtil.getByJson(jsonMsg, SupplyCfg.class);
            if (supplyCfg == null) return;

            //找出被指派人
            VendingMachineViewModel vm = vmService.getVMInfo(supplyCfg.getInnerCode());
            Integer assignId = taskService.getLeastuser(vm.getRegionId(), false);
            //创建补货工单
            TaskViewModel taskViewModel = new TaskViewModel();
            taskViewModel.setUserId(1);//自动默认为管理员操作人
            taskViewModel.setAssignorId(assignId);
            taskViewModel.setCreateType(0);//自动创建类型
            taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);
            taskViewModel.setInnerCode(supplyCfg.getInnerCode());
            taskViewModel.setDesc("自动补货工单");

            taskViewModel.setDetails(supplyCfg.getSupplyData().stream().map(c->{
                TaskDetailsViewModel taskDetailsViewModel = new TaskDetailsViewModel();
                taskDetailsViewModel.setChannelCode(c.getChannelId());
                taskDetailsViewModel.setExpectCapacity(c.getCapacity());
                taskDetailsViewModel.setSkuId(c.getSkuId());
                taskDetailsViewModel.setSkuName(c.getSkuName());
                taskDetailsViewModel.setSkuImage(c.getSkuImage());
                return taskDetailsViewModel;
            }).collect(Collectors.toList()));
            taskService.createTask(taskViewModel);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("创建自动补货工单出错" + e.getMessage());
        }

    }
}
